package com.msh.bird;

import javax.sound.sampled.*;
import java.io.IOException;

/**
 * Date：2021年09月
 * Author：程Sir
 * Content: 音频播放类
 */
public class Music {
    /**
     * 每次IO流读取的字节大小
     */
    private byte[] data;
    /**
     * 音频格式对象
     */
    private AudioFormat format;
    /**
     * 读取的数据大小
     */
    private int length;

    public Music(String music) throws IOException, UnsupportedAudioFileException {
        AudioInputStream in = AudioSystem.getAudioInputStream(getClass().getResource(music));
        format = in.getFormat();
        length = (int) in.getFrameLength();
        data = new byte[length];
        in.read(data);
        // 关闭！
        in.close();
    }

    /**
     * 播放音频的功能
     */
    public void play(){
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Clip clip = AudioSystem.getClip();
                    clip.open(format, data, 0 ,length);
                    clip.start();
                    clip.drain();
                    clip.stop();
                    clip.close();

                } catch (LineUnavailableException e) {
                    e.printStackTrace();
                }
            }
        };

        // 启动线程开始运行
        new Thread(runnable);
    }

}
